package org.nebuloop.photo.organizer;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang.StringUtils;

public class SkippedFileLogger implements AutoCloseable {
  private final AtomicLong skippedFileCount = new AtomicLong(0);
  private PrintWriter skippedFileLog;

  public SkippedFileLogger(String strFile) throws IOException {
    this.skippedFileLog = new PrintWriter(strFile);
  }

  public SkippedFileLogger(PrintWriter skippedFileLog) {
    this.skippedFileLog = skippedFileLog;
  }

  public long getSkippedFileCount() {
    return skippedFileCount.get();
  }

  public PrintWriter getSkippedFileLog() {
    return skippedFileLog;
  }

  public void setSkippedFileLog(PrintWriter skippedFileLog) {
    this.skippedFileLog = skippedFileLog;
  }

  public void logFileSkipEvent(String filePath, String message, Exception ex) {
    skippedFileCount.incrementAndGet();
    if (skippedFileLog != null) {
      synchronized (skippedFileLog) {
        skippedFileLog.print(filePath);
        skippedFileLog.print("\t:\t");
        if (StringUtils.isNotBlank(message)) {
          skippedFileLog.print(message);
        }
        if (ex != null) {
          skippedFileLog.print(ex.toString());
        }
        skippedFileLog.println();
      }
    }
  }

  public void logFileSkipEvent(File filePath, String message, Exception ex) {
    logFileSkipEvent(filePath.getAbsolutePath(), message, ex);
  }

  @Override
  public void close() throws Exception {
    if (skippedFileLog != null) {
      skippedFileLog.close();
    }
  }
}
